package com.du.ichat;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.du.ichat.utils.BaseActivity;
import com.du.ichat.utils.DialogUtils;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.friend.FriendService;
import com.netease.nimlib.sdk.friend.constant.VerifyType;
import com.netease.nimlib.sdk.friend.model.AddFriendData;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.ArrayList;
import java.util.List;

public class UserInfoActivity extends BaseActivity {
    private final static int GET_USER_INFO_FINISH = 1;
    private Toolbar toolbar;
    private String account;
    private Handler handler = new UserInfoHelper();
    private ImageView ivAvatar , ivGender;
    private TextView tvNmae,tvAccount,tvInfo,tvAddr;
    private View photoLayout;
    private Button btnSendMessage ,btnAddFriend;
    private ImageButton btnBack;
    private android.support.v4.app.DialogFragment loadingDialog;
    private NimUserInfo friend;
    private boolean isMyFriend;
    private Dialog deteleDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        loadingDialog = DialogUtils.getDialog();
        loadingDialog.show(getSupportFragmentManager() , "dialog");
        account = getIntent().getStringExtra("account");
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        initView();
        isMyFriend = NIMClient.getService(FriendService.class).isMyFriend(account);
        if(isMyFriend){
            btnSendMessage.setVisibility(View.VISIBLE);
            btnAddFriend.setVisibility(View.GONE);
        }else{
            btnSendMessage.setVisibility(View.GONE);
            btnAddFriend.setVisibility(View.VISIBLE);
        }

        getUserinfo();

        log("ismyfriend : " + isMyFriend);

        DialogUtils.dismiss(loadingDialog , this);



    }



    private void initView() {
        ivAvatar = findViewById(R.id.userinfo_avatar);
        ivGender = findViewById(R.id.userinfo_gender);
        tvNmae = findViewById(R.id.userinfo_name);
        tvAccount = findViewById(R.id.userinfo_account);
        tvAddr = findViewById(R.id.userinfo_tv_addr);
        photoLayout = findViewById(R.id.user_photo_layout);
        tvInfo = findViewById(R.id.userinfo_tv_info);
        btnSendMessage = findViewById(R.id.btnsendmessage);
        btnAddFriend = findViewById(R.id.btnaddfriend);
        btnBack = findViewById(R.id.back);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        btnAddFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addFriend();
            }
        });
        btnSendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(UserInfoActivity.this , ChatActivity.class);
                intent.putExtra("friendInfo" , friend);
                startActivity(intent);
                finish();
            }
        });
    }

    private void addFriend() {
        final VerifyType verifyType = VerifyType.DIRECT_ADD; // 发起好友验证请求
        String msg = "好友请求附言";
        NIMClient.getService(FriendService.class).addFriend(new AddFriendData(account, verifyType, msg))
                .setCallback(new RequestCallback<Void>() {

                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.e("Tag" , "success");
                        toast("添加成功");
                        finish();
                    }

                    @Override
                    public void onFailed(int i) {
                        Log.e("Tag" , "fail : " + i);
                    }

                    @Override
                    public void onException(Throwable throwable) {

                    }
                });
    }


    private void getUserinfo(){
        List<String> accounts = new ArrayList<>();
        accounts.add(account);
        NIMClient.getService(UserService.class).fetchUserInfo(accounts).setCallback(new RequestCallback<List<NimUserInfo>>() {
            @Override
            public void onSuccess(List<NimUserInfo> nimUserInfos) {
                if(nimUserInfos.size() > 0){
                    friend = nimUserInfos.get(0);
                    Message msg = handler.obtainMessage(GET_USER_INFO_FINISH);
                    msg.obj = nimUserInfos.get(0);
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onFailed(int i) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
    }



    private class UserInfoHelper extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET_USER_INFO_FINISH:
                    showUserInfo((NimUserInfo) msg.obj);
                    break;
            }
        }
    }

    private void showUserInfo(NimUserInfo userinfo) {
        tvNmae.setText(userinfo.getName());
        tvAccount.setText("微信号:" + userinfo.getAccount());
        if(userinfo.getExtensionMap() !=null && userinfo.getExtensionMap().containsKey("country")){
            tvAddr.setText(userinfo.getExtensionMap().get("country").toString());
        }else{
            tvAddr.setText("未知");
        }
        tvInfo.setText(TextUtils.isEmpty(userinfo.getSignature()) ? "未设置" : userinfo.getSignature());
        GlideApp.with(this).load(userinfo.getAvatar()).placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar).into(ivAvatar);
        Glide.with(this).load(userinfo.getGenderEnum().getValue() == 1?R.drawable.man :R.drawable.woman).into(ivGender);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if(isMyFriend){
            getMenuInflater().inflate(R.menu.menu_userinfo , menu);
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.action_delete_friend){
            deteleDialog = createDeleteDialog();
            deteleDialog.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private void deleteFirend(){

        NIMClient.getService(FriendService.class).deleteFriend(account)
                .setCallback(new RequestCallback<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        log("delete success");
                        deteleDialog.dismiss();
                        toast("已删除联系人");
                        finish();

                    }

                    @Override
                    public void onFailed(int i) {
                        log("delete onFailed" + i);
                        deteleDialog.dismiss();
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        log("delete onException");
                        deteleDialog.dismiss();
                    }
                });
    }


    public Dialog createDeleteDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_delete_friend , null , false);
        TextView tvMessage = view.findViewById(R.id.tvMessage);
        TextView tvDelete = view.findViewById(R.id.tvDelete);
        TextView tvCanel = view.findViewById(R.id.tvcanel);
        tvMessage.setText(getString(R.string.deleteFriendMessage , friend.getName()));
        builder.setView(view);

        final Dialog dialog = builder.create();
        tvCanel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(dialog != null){
                    dialog.dismiss();
                }
            }
        });



        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteFirend();
            }
        });

        return dialog;
    }


}
